<template>
  <el-card class="spu-card">
    <el-form
      label-width="100px"
      ref="spuFormRef"
      :model="spuFormData"
      :rules="spuFormRules"
    >
      <el-form-item label="SPU名称" prop="spuName">
        <el-input placeholder="SPU名称" v-model="spuFormData.spuName" />
      </el-form-item>
      <el-form-item label="品牌" prop="tmId">
        <el-select placeholder="请选择品牌" v-model="spuFormData.tmId">
          <el-option
            v-for="tm in trademarkList"
            :key="tm.id"
            :label="tm.tmName"
            :value="tm.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input
          placeholder="SPU描述"
          :rows="2"
          type="textarea"
          v-model="spuFormData.description"
        />
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload
          v-model:file-list="spuFormData.spuImageList"
          :action="UPLOAD_URL_PREFIX + '/admin/product/fileUpload'"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAvatarUpload"
          :limit="MAX_LIMIT_LENGTH"
          :on-success="handleSuccess"
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过200kb</div>
          </template>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img class="spu-img" :src="dialogImageUrl" alt="预览图片" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select
          :placeholder="`还剩 ${filterBaseSaleAttrList.length} 个未选择`"
          v-model="selectedSaleAttr"
        >
          <el-option
            v-for="baseSaleAttr in filterBaseSaleAttrList"
            :key="baseSaleAttr.id"
            :label="baseSaleAttr.name"
            :value="`${baseSaleAttr.id}:${baseSaleAttr.name}`"
          />
        </el-select>
        <el-button
          type="primary"
          :icon="Plus"
          class="spu-btn"
          :disabled="!selectedSaleAttr"
          @click="addSaleAttr"
        >
          添加销售属性
        </el-button>
        <el-table :data="spuFormData.spuSaleAttrList" border class="spu-table">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="60"
          />
          <el-table-column label="属性名" prop="saleAttrName" width="200" />

          <el-table-column label="属性值名称列表">
            <template v-slot="{ row }">
              <el-tag
                closable
                v-for="(saleAttrValue, index) in row.spuSaleAttrValueList"
                :key="saleAttrValue.saleAttrValueName"
                class="spu-tag"
                @close="delSaleAttrValue(row, index)"
              >
                {{ saleAttrValue.saleAttrValueName }}
              </el-tag>
              <!-- 编辑模式 -->
              <el-input
                placeholder="请输入属性值名称"
                size="small"
                class="spu-input"
                v-if="row.isEdit"
                ref="inputRef"
                v-model="saleAttrValueName"
                @blur="addSaleAttrValueName(row)"
                @keyup.enter="addSaleAttrValueName(row)"
              />
              <!-- 显示模式 -->
              <el-button
                :icon="Plus"
                size="small"
                v-else
                @click="showEdit(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template v-slot="{ $index }">
              <el-tooltip content="删除销售属性" placement="top" effect="light">
                <el-button
                  type="danger"
                  :icon="Delete"
                  size="small"
                  @click="delSaleAttr($index)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="goSpuList">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "SaveOrUpdateSpu",
};
</script>

<script lang="ts" setup>
import { onMounted, ref, reactive, computed, nextTick } from "vue";
import { Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules, UploadProps } from "element-plus";
import { getAllTrademarkListApi } from "@/api/product/trademark";
import {
  getBaseSaleAttrListApi,
  saveSpuApi,
  getSpuImageListApi,
  getSpuSaleAttrListApi,
  updateSpuApi,
} from "@/api/product/spu";
import type { TrademarkList } from "@/api/product/model/trademarkModel";
import type {
  BaseSaleAttrList,
  SpuFormData,
  SaveSpuSaleAttrItem,
  SaveSpuSaleAttrList,
} from "@/api/product/model/spuModel";
import { useCategoryStore } from "@/stores/category";

const trademarkList = ref<TrademarkList>([]);
const baseSaleAttrList = ref<BaseSaleAttrList>([]);

onMounted(async () => {
  // Promise.all/allSettled
  trademarkList.value = await getAllTrademarkListApi();
});

onMounted(async () => {
  baseSaleAttrList.value = await getBaseSaleAttrListApi();
});

onMounted(async () => {
  const { id } = spuFormData;
  // 添加不需要，更新才需要
  if (!id) return;
  const res = await getSpuImageListApi(id);
  spuFormData.spuImageList = res.map((img) => {
    return {
      name: img.imgName,
      url: img.imgUrl,
    };
  });
});

onMounted(async () => {
  const { id } = spuFormData;
  // 添加不需要，更新才需要
  if (!id) return;
  spuFormData.spuSaleAttrList = await getSpuSaleAttrListApi(id);
});

const props = defineProps<{
  spu: SpuFormData;
}>();

// 表单实例
const spuFormRef = ref<FormInstance>();
// 表单数据
const spuFormData = reactive<SpuFormData>(props.spu);
// 表单校验规则
const spuSaleAttrListValidator = (
  rule: any,
  value: SaveSpuSaleAttrList,
  callback: any
) => {
  /*
    value 校验表单的数据
    callback 函数，必须要调用
      callback() 代表校验通过
      callback(new Error('xxx')) 代表校验失败

    1. 至少添加一个销售属性
    2. 每个销售属性至少添加一个属性值
  */
  // 1. 至少添加一个销售属性
  if (!value.length) {
    callback(new Error("请至少添加一个销售属性"));
    return;
  }

  // 2. 每个销售属性至少添加一个属性值
  // if (value.some((saleAttr) => !saleAttr.spuSaleAttrValueList.length)) {
  if (!value.every((saleAttr) => saleAttr.spuSaleAttrValueList.length)) {
    callback(new Error("每个销售属性至少添加一个属性值"));
    return;
  }

  // 校验通过
  callback();
};
// https://gitee.com/mirrors/async-validator#rules
const spuFormRules = reactive<FormRules>({
  spuName: [{ required: true, message: "请输入SPU名称", trigger: "blur" }],
  tmId: [{ required: true, message: "请选择SPU品牌", trigger: "change" }],
  description: [{ required: true, message: "请输入SPU描述", trigger: "blur" }],
  spuImageList: [{ required: true, message: "请上传SPU图片" }],
  spuSaleAttrList: [
    {
      required: true,
      // 自定义校验规则
      validator: spuSaleAttrListValidator,
    },
  ],
});

// 请求前缀
const UPLOAD_URL_PREFIX = import.meta.env.VITE_API_URL;
// 最大上传图片的数量
const MAX_LIMIT_LENGTH = 10;

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
// 预览图片
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url as string;
  dialogVisible.value = true;
};

// 上传之前触发的函数：限制图片的大小和类型
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // 定义合法的图片类型数组
  const imageTypes = ["image/jpeg", "image/jpg", "image/png"];

  if (!imageTypes.includes(rawFile.type)) {
    ElMessage.error("上传的图片必须是jpg或png格式!");
    return false;
    // rawFile.size 上传的文件大小
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("上传的图片不能超过200kb!");
    return false;
  }

  return true;
};

// 上传成功的回调
const handleSuccess = () => {
  if (spuFormData.spuImageList.length === 1) {
    spuFormRef.value?.clearValidate(["spuImageList"]);
  }
};

// 上传按钮显示隐藏
const uploadBtnDisplay = computed(() => {
  return spuFormData.spuImageList.length < MAX_LIMIT_LENGTH
    ? "inline-flex"
    : "none";
});

// 选中的销售属性
const selectedSaleAttr = ref("");

// 添加销售属性
const addSaleAttr = () => {
  const [id, name] = selectedSaleAttr.value.split(":");

  spuFormData.spuSaleAttrList.push({
    baseSaleAttrId: +id,
    saleAttrName: name,
    spuSaleAttrValueList: [],
    isEdit: false,
  });

  selectedSaleAttr.value = "";
};

// 删除销售属性
const delSaleAttr = (index: number) => {
  spuFormData.spuSaleAttrList.splice(index, 1);
};

const inputRef = ref();

// 点击显示模式的按钮进入编辑模式
const showEdit = async (row: SaveSpuSaleAttrItem) => {
  row.isEdit = true;
  await nextTick();
  inputRef.value.focus();
};

// 收集的销售属性值名称
const saleAttrValueName = ref("");

// 编辑默认失去焦点，添加销售属性值
const addSaleAttrValueName = (row: SaveSpuSaleAttrItem) => {
  if (saleAttrValueName.value) {
    row.spuSaleAttrValueList.push({
      baseSaleAttrId: row.baseSaleAttrId,
      saleAttrValueName: saleAttrValueName.value,
    });

    saleAttrValueName.value = "";
  }
  // 显示模式
  row.isEdit = false;
};

// 销售销售属性值
const delSaleAttrValue = (row: SaveSpuSaleAttrItem, index: number) => {
  row.spuSaleAttrValueList.splice(index, 1);
};

// 销售属性
const filterBaseSaleAttrList = computed(() => {
  // 遍历所有基础销售属性列表，判断销售属性在不在table的数组（spuFormData.spuSaleAttrList)中
  // 在，过滤
  // 不在，保留
  return baseSaleAttrList.value.filter((baseSaleAttr) => {
    // 返回true保留，返回false是过滤
    /*
      {
        "baseSaleAttrId": 0, // 基础销售id
        "saleAttrName": "string", // 基础销售属性名称
        "spuSaleAttrValueList": [] // 销售属性值列表
      }
    */
    return !spuFormData.spuSaleAttrList.some(
      (saleAttr) => saleAttr.baseSaleAttrId === baseSaleAttr.id
    );
  });
});

const emit = defineEmits(["setIsShow"]);

// 取消
const goSpuList = () => {
  emit("setIsShow", 1);
};

const categoryStore = useCategoryStore();
// 提交表单
const submitForm = async () => {
  await spuFormRef.value?.validate();

  const data = {
    ...spuFormData,
    tmId: spuFormData.tmId as number,
    spuImageList: spuFormData.spuImageList.map((img) => {
      return {
        imgName: img.name,
        // imgUrl: (img.response as { data: string }).data,
        /*
          SaveOrUpdateSpu.vue:382 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data')
            at SaveOrUpdateSpu.vue:382:52

          更新：
            请求回来的图片只有url
            新上传的图片才有response.data
          
          判断是否是新上传的图片，是上传得到的图片地址 img.response.data
          不是，就用原有地址 img.url
        */
        imgUrl: img.response ? (img.response as any).data : img.url,
      };
    }),
    category3Id: categoryStore.category3Id as number,
  };

  if (spuFormData.id) {
    await updateSpuApi(data);
  } else {
    await saveSpuApi(data);
  }

  ElMessage.success(`${spuFormData.id ? "更新" : "添加"}SPU成功`);

  goSpuList();
};
</script>

<style scoped lang="scss">
.spu-card {
  margin-top: 20px;
}
.spu-table {
  margin-top: 10px;
}
.spu-btn {
  margin-left: 10px;
}
.spu-tag {
  margin-right: 10px;
}
.spu-img {
  width: 100%;
}

.spu-input {
  width: 200px;
}
// .spu-card :deep(.el-upload) {
//   display: v-bind(uploadBtnDisplay);
// }

.spu-card :deep() {
  .el-upload {
    display: v-bind(uploadBtnDisplay);
  }
}
</style>
